package com.kitty.game.bag;

import com.kitty.common.utils.SpringUtils;
import com.kitty.game.attribute.AttrService;
import com.kitty.game.bag.message.*;
import com.kitty.game.bag.model.StoreEquipInfo;
import com.kitty.game.base.service.BagService;
import com.kitty.game.config.Equip;
import com.kitty.game.config.PetStore;
import com.kitty.game.equip.EquipDataPool;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.fly.FlyTypeEnums;
import com.kitty.game.item.service.ChangeCardService;
import com.kitty.game.onlinemall.service.MallService;
import com.kitty.game.pet.message.RespPetHost;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.service.PetService;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.skill.message.RespUpdateSkill;
import com.kitty.game.skill.message.vo.SkillInfo;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.team.model.Member;
import com.kitty.game.team.model.Team;
import com.kitty.game.team.service.TeamService;
import com.kitty.game.utils.AsktaoUtil;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.JsonUtils;
import com.kitty.listener.EventDispatcher;
import com.kitty.listener.EventType;
import com.kitty.listener.event.ChangeEquipEvent;
import com.kitty.listener.event.OnEquipEvent;
import com.kitty.mina.annotation.RequestMapping;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.MessagePusher;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.*;

@Controller
@Slf4j
public class BagController {


    @Resource
    AttrService attrService;
    @Autowired
    TeamService teamService;
    @Autowired
    RoleService roleService;
    /**
     * 存入宝宝
     */
    @RequestMapping
    public void savePet(IoSession session, ReqSavePet reqSavePet) {
        PetService petService = SpringUtils.getBean(PetService.class);
        Role role = SessionUtils.getRoleBySession(session);
        PetStore petStore = role.getPetBox().getPetStore();
        Map<Short, Integer> hashMap = petStore.getPetInfo();

        if (reqSavePet.getType() == 1) {//存入
            Pet pet = petService.getPetByPos((byte) reqSavePet.getPos(), role);
            if(StringUtils.isNotEmpty(pet.getGongSheng_pet_id())){
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("共生宠物无法放入仓库。"));
                return ;
            }
            if (pet == null) {
                return;
            }
            short pos = petService.getPetStoreNull(role, session);
            if (pos < 0) {
                return;
            }

            boolean istrue = false;
            for (Map.Entry<Short, Integer> entry : hashMap.entrySet()) {
                if (entry.getValue() == pet.getId()) {
                    istrue = true;
                    break;
                }
            }
            if (!istrue) {//仓库里没有这个宠物 存入
                pet.setInStore(true);
                RespPetHost respPetHost = new RespPetHost();
                respPetHost.setPetId(pet.getId());
                MessagePusher.pushMessage(session, respPetHost);

                hashMap.put(pos, pet.getId());
                petService.sendPetStore(role, pos, pet);
            }
        } else {
            short pos = reqSavePet.getPos();
            Iterator<Map.Entry<Short, Integer>> it = hashMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<Short, Integer> next = it.next();
                short storePos = next.getKey();
                if (storePos == pos) {
                    Pet pet = role.getPetBox().getStorePetByPosition(storePos);
                    if (pet != null) {
                        RespUpdateSkill respUpdateSkill = new RespUpdateSkill();
                        respUpdateSkill.setId(pet.getId());
                        ArrayList<SkillInfo> arrayList = new ArrayList<>();
                        respUpdateSkill.setList(arrayList);
                        MessagePusher.pushMessage(session, respUpdateSkill);
                        petService.loadPet(role, pet);
                        pet.setInStore(false);
                        RespIconCartoon respIconCartoon = new RespIconCartoon();
                        respIconCartoon.setType((short) 2);
                        respIconCartoon.setName(pet.getName());
                        respIconCartoon.setParam(pet.getIcon() + "");
                        MessagePusher.pushMessage(session, respIconCartoon);

                        petService.sendNullPetStore(session, next.getKey());
                        it.remove();
                    }
                }
            }

        }

        role.save();
    }


    /**
     * 使用物品
     */
    @RequestMapping
    public void itemUse(IoSession session, ReqItemUse reqItemUse) {
        EquipService equipService = SpringUtils.getBean(EquipService.class);
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) {
            return;
        }
        if (reqItemUse.getNum() <= 0) {
            return;
        }
        int newPos = reqItemUse.getPos() & 0x0FF;

        RoleEquip roleEquip = equipService.getRoleEquipByPos(role, newPos);
        if (roleEquip == null){
            return;
        }
        if (role.getLevel() < 30 && roleEquip.getName().contains("礼包")){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("等级不足#R30级#n，不能使用礼包！！！"));
            return;
        }
        if (role.getLevel() < 188 && roleEquip.getName().contains("力破进阶书")){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("#R此道具只能在npc处使用"));
            return;
        }
        if (role.getLevel() < 188 && roleEquip.getName().contains("五法进阶书")){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("#R此道具只能在npc处使用"));
            return;
        }
        if (role.getLevel() < 188 && roleEquip.getName().contains("周年卡")){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("#R此道具只能在npc处使用"));
            return;
        }
        if (role.getLevel() < 188 && roleEquip.getName().contains("转生令牌")){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("#R此道具只能在npc处使用"));
            return;
        }
        if (role.getLevel() < 188 && roleEquip.getName().contains("神魂突破书")){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("#R此道具只能在npc处使用"));
            return;
        }
        if (role.getLevel() < 188 && roleEquip.getName().contains("武魂突破书")){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("#R此道具只能在npc处使用"));
            return;
        }if (role.getLevel() < 188 && roleEquip.getName().contains("小型炸弹")){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("#R此道具不能直接使用，发送弹幕会自动扣除"));
            return;
        }if (role.getLevel() < 188 && roleEquip.getName().contains("宠物顿悟丹")){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("#R此道具不能直接使用，请到宠物 技能-顿悟 页面使用"));
            return;
        }if (role.getLevel() < 188 && roleEquip.getName().contains("桃子")){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("#R此道具不能直接使用，请到千面怪处提交"));
            return;
        }if (role.getLevel() < 188 && roleEquip.getName().contains("萝卜")){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("#R此道具不能直接使用，请到千面怪处提交用"));
            return;
        }if (role.getLevel() < 188 && roleEquip.getName().contains("大桃子")){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("#R此道具不能直接使用，请到千面怪处提交"));
            return;
        }if (role.getLevel() < 188 && roleEquip.getName().contains("大萝卜")){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("#R此道具不能直接使用，请到千面怪处提交"));
            return;
        }if (role.getLevel() < 188 && roleEquip.getName().contains("万能碎片")){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("#R此道具不能直接使用，请到稀有物品兑换NPC处使用"));
            return;
        }if (role.getLevel() < 188 && roleEquip.getName().contains("凝神草")){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("#R此道具不能直接使用，请到鬼宠凝神页面使用"));
            return;
        }
     //   logger.info("物品名称==={111111111111111}===物品位置==={1111111111}");

        if (roleEquip != null && roleEquip.queryNum() >= reqItemUse.getNum()) {
            equipService.useItem(reqItemUse.getPos(), reqItemUse.getNum(), session);
        }

    }

    /**
     * 存钱
     */
    @RequestMapping
    public void saveMoney(IoSession session, ReqSaveMoney reqSaveMoney) {
        RoleService roleService = SpringUtils.getBean(RoleService.class);
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) {
            return;
        }
        if (reqSaveMoney.getSaveMoney() <= 0 || role.getMoney() <= 0 || role.getMoney() < reqSaveMoney.getSaveMoney()) {
            return;
        }
        long storeMoney = role.getStoreMoney();
        long total = storeMoney + reqSaveMoney.getSaveMoney();
        if (total >= 2000000000) {
            return;
        }

        role.setStoreMoney((int) total);
        roleService.subtractMoney(role,  reqSaveMoney.getSaveMoney());
        RespIconCartoon respIconCartoon = new RespIconCartoon();
        respIconCartoon.setType((short) 6);
        respIconCartoon.setName("金钱");
        respIconCartoon.setParam(reqSaveMoney.getSaveMoney() + "");
        MessagePusher.pushMessage(session, respIconCartoon);
        roleService.updateSaveMoney(role);
        MessagePusher.pushMessage(session, new RespNotifyMiscEx("成功存入" + AsktaoUtil.getMoneyFormat(reqSaveMoney.getSaveMoney()) + "#n文钱#n。"));
        role.save();
    }

    /**
     * 取钱
     */
    @RequestMapping
    public void getSaveMoney(IoSession session, ReqGetSaveMoney reqGetSaveMoney) {
        RoleService roleService = SpringUtils.getBean(RoleService.class);
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) {
            return;
        }
        log.error("仓库取钱=roleId={}={}", role.getRoleId(), reqGetSaveMoney.getSaveMoney());
        if (reqGetSaveMoney.getSaveMoney() < 0 || role.getStoreMoney() < reqGetSaveMoney.getSaveMoney()) {
            return;
        }
        if ((role.getMoney() + reqGetSaveMoney.getSaveMoney()) > 2000000000) {
            return;
        }
        role.setStoreMoney(role.getStoreMoney() - reqGetSaveMoney.getSaveMoney());
        roleService.addMoney(role, reqGetSaveMoney.getSaveMoney());

        RespIconCartoon respIconCartoon = new RespIconCartoon();
        respIconCartoon.setType((short) 7);
        respIconCartoon.setName("金钱");
        respIconCartoon.setParam(reqGetSaveMoney.getSaveMoney() + "");
        MessagePusher.pushMessage(session, respIconCartoon);
        roleService.updateSaveMoney(role);
        MessagePusher.pushMessage(session, new RespNotifyMiscEx("成功取出" + AsktaoUtil.getMoneyFormat(reqGetSaveMoney.getSaveMoney()) + "#n文钱#n。"));
        role.save();

    }

    /**
     * 仓库中取出
     *
     * @param session
     * @param reqTake
     */
    @RequestMapping
    public void take(IoSession session, ReqTake reqTake) {
        Role role = SessionUtils.getRoleBySession(session);

        BagService bagService = SpringUtils.getBean(BagService.class);
        short newPos = bagService.getPos(session, false);
        if (newPos <= 0) {
            MessagePusher.pushMessage(session, new RespMsg("你的包裹已满，还是整理后再来吧。"));
            return;
        }
        short storePos = reqTake.getFrom_pos();
        if (storePos <= 200) {
            return;
        }
        EquipService equipService = SpringUtils.getBean(EquipService.class);
        RoleEquip resultEquip = equipService.getRoleEquipByPos(role, storePos);
        if (resultEquip == null) {
            return;
        }
        resultEquip.setPosition(newPos);

        String type = storePos >= 2001 && storePos <= 2501 ? "card_store" : "normal_store";

        if (!type.equals("card_store")) {
            RespIconCartoon respIconCartoon = new RespIconCartoon();
            respIconCartoon.setName(resultEquip.getName());
            respIconCartoon.setParam("0");
            MessagePusher.pushMessage(session, respIconCartoon);
        } else {
            MessagePusher.pushMessage(session, new RespMsg("已将" + resultEquip.getName() + "成功取出到包裹。"));
        }


        // 发送消失包
        ArrayList<StoreEquipInfo> storeEquipInfos = new ArrayList<>();
        StoreEquipInfo storeEquipInfo = new StoreEquipInfo();
        storeEquipInfo.setPos(storePos);
        storeEquipInfos.add(storeEquipInfo);
        RespStore respStore = new RespStore();
        respStore.setStr(type);
        respStore.setList(storeEquipInfos);
        MessagePusher.pushMessage(session, respStore);

        equipService.refreshRoleEquip(role, resultEquip);

        role.save();
    }

    /**
     * 卸下装备
     *
     * @param session
     * @param reqUnequip
     */
    @RequestMapping
    public void unEquip(IoSession session, ReqUnequip reqUnequip) {
        Role role = SessionUtils.getRoleBySession(session);
        byte oldPos = reqUnequip.getOldPos();
        int newPos = reqUnequip.getNewPos() & 0x0FF;

        /**如果要卸下的装备不在备用装备或者主装备页*/
        if (!Const.BACK_PAGE.contains(oldPos) && !Const.MAIN_PAGE.contains(oldPos)) {
            return;
        }
        if (newPos <= 40) {
            return;
        }
        EquipService equipService = SpringUtils.getBean(EquipService.class);
        RoleEquip resultEquip = equipService.getRoleEquipByPos(role, oldPos);
        if (resultEquip == null) {
            return;
        }

        resultEquip.setPosition(newPos);
        equipService.setPositionNull(role, (byte) oldPos);
        // 是否有套装效果

        /**产生一个装备改变事件*/
        EventDispatcher.getInstance().fireEvent(new ChangeEquipEvent(EventType.CHANGE_EQUIP, role, resultEquip));
        //判断如果是40是飞行器 并且是队长 。就要刷新队伍里面每个人的外观
        if(teamService.isTeamLeader(role) && oldPos==40){
            Team team = teamService.getTeam(role.getRoleId());
            for (Member member : team.getList()) {
                Role memberRole = roleService.getOnlinePlayer(member.getUid());
                if(memberRole !=null && member.isInTeam()){
                    SpringUtils.getBroadcastService().sendUpdateAppear(memberRole);
                }
            }
        }else{
            SpringUtils.getBroadcastService().sendUpdateAppear(role);
        }
        role.save();

    }

    /**
     * 存入仓库
     *
     * @param session
     * @param reqStore
     */
    @RequestMapping
    public void saveEquip(IoSession session, ReqStore reqStore) {
        Role role = SessionUtils.getRoleBySession(session);
        log.info("saveEquip{}，{}", role.getUid(), reqStore.getAmount());
        BagService bagService = SpringUtils.getBean(BagService.class);
        EquipService equipService = SpringUtils.getBean(EquipService.class);
        short position = reqStore.getFrom_pos();
        String dest = reqStore.getContainer();
        RoleEquip resultEquip = equipService.getRoleEquipByPos(role, position);
        if (resultEquip == null) {
            return;
        }
        if (dest.equals("normal_store")) {
            short resultPos = bagService.getPos(session, true);
            if (resultPos <= 0) {
                MessagePusher.pushMessage(session, new RespMsg("仓库已满，无法存放更多物品。"));
                return;
            }
            resultEquip.setPosition(resultPos);
            // 消失
            equipService.setPositionNull(role, (byte) position);
            // 仓库显示
            bagService.sendOneStore(resultPos, role, resultEquip);
        } else if (dest.equals("card_store")) {//变身卡仓库
            SpringUtils.getBean(ChangeCardService.class).saveCard(role, resultEquip);
        }

        role.save();
    }


    /**
     * 整理背包
     */
    @RequestMapping
    public void sortPack(IoSession session, ReqSortPack reqSortPack) {
        Role role = SessionUtils.getRoleBySession(session);
        SpringUtils.getBean(BagService.class).sortPack(role, reqSortPack);
        role.save();
    }
    /**
     * 佩戴装备
     *
     * @param session
     * @param reqEquip
     */
    @RequestMapping
    public void equip(IoSession session, ReqEquip reqEquip) {
        Role role = SessionUtils.getRoleBySession(session);
        int from = reqEquip.getFrom() & 0x0FF;
        byte to = reqEquip.getTo();

        if (from <= 40) {
            return;
        }
        /**不管当前在第几页装备 穿戴的时候位置都是主装备页*/
        if (!Const.MAIN_PAGE.contains(to)) {
            return;
        }

        BagService bagService = SpringUtils.getBean(BagService.class);
        EquipService equipService = SpringUtils.getBean(EquipService.class);
        RoleEquip fromEquip = equipService.getRoleEquipByPos(role, from);
        RoleEquip toEquip = equipService.getRoleEquipByPos(role, to);

        if (fromEquip == null) {
            return;
        }
        Equip equip = EquipDataPool.getByName(fromEquip.getName());
        if (equip == null) {
            return;
        }
        // 武器是否可以佩戴
        if (to == Const.WEAPON) {
            if (equip.getPosition() != to) {
                return;
            }
            if (role.getPolar() != equip.getMenpai()) {
                MessagePusher.pushMessage(session, new RespMsg("角色不符，不能装备！"));
                return;
            }
        }
        if (to == Const.HELMET || to == Const.ARMOR) {
            if (equip.getPosition() != to) {
                return;
            }
            if (equip.getGender() != role.getGender() && equip.getGender() != 0) {
                MessagePusher.pushMessage(session, new RespMsg("性别不符，不能装备！"));
                return;
            }
        }
        if (to == Const.NECKLACE || to == Const.BALDRIC || to == Const.LEFT_WRIST || to == Const.ARTIFACT || to == Const.BOOT || to == Const.TALISMAN) {
            if (equip.getPosition() != to) {
                return;
            }
        } else if (to == Const.RIGHT_WRIST) {
            if (equip.getPosition() != to - 1) {
                return;
            }
        }
        if (equip.getReq_level() > role.getLevel() && (fromEquip.getType().equals("装备") || fromEquip.getType().endsWith("首饰") || fromEquip.getType().startsWith("魂器"))) {
            MessagePusher.pushMessage(session, new RespMsg("等级不足，不能装备！"));
            return;
        }

        if (!fromEquip.getType().equals("装备") && !fromEquip.getType().equals("法宝") && !fromEquip.getType().endsWith("首饰") && !fromEquip.getType().startsWith("魂器")&& !fromEquip.getType().startsWith("飞行器")) {
            return;
        }

        /**如果穿戴的装备数量大于1 一般只有低级首饰会出现 克隆一件装备带上 扣除数量*/
        int count = fromEquip.queryNum();
        if (count > 1) {
            RoleEquip newEquip = JsonUtils.cloneObject(fromEquip);
            newEquip.alterNum(1);
            newEquip.setId(SpringUtils.getBean(MallService.class).getRoleEquipId());
            newEquip.alterId(newEquip.getId());
            newEquip.alterGid(String.valueOf(newEquip.getId()));
            newEquip.setPosition(to);
            equipService.add(role, newEquip);

            /**把装备到身上的装备数量设置成1*/
            fromEquip.alterNum(count - 1);
            equipService.refreshRoleEquip(role, fromEquip);
        } else {
            fromEquip.setPosition(to);
            equipService.setPositionNull(role, (byte) from);
        }

        if (toEquip != null) {
            short pos = bagService.getPos(session, false);
            if (pos <= 0) {
                pos = (short) from;
            }
            toEquip.setPosition(pos);
            toEquip.alterSuitEnabled(0);
            toEquip.getFields().remove((short) 7426);
            equipService.refreshRoleEquip(role, toEquip);

            /**需要判断一下新手礼包送的装备 永久限制的装备直接出售*/
            List<Integer> EQUIP_POS= Arrays.asList(1,2,3,10);
            if(toEquip.queryLevel()<= 70 && toEquip.isEverLimit() && EQUIP_POS.contains((int)toEquip.queryEquipPos(false)) ){
                SpringUtils.getBean(EquipService.class).soldToSystem(role,toEquip.getPosition(), (short) 1);
            }
        }

        /**产生一个穿戴装备事件*/
        EventDispatcher.getInstance().fireEvent(new OnEquipEvent(EventType.ON_EQUIP, role, equip.getKey_name(),fromEquip));

        /**产生一个装备改变事件*/
        EventDispatcher.getInstance().fireEvent(new ChangeEquipEvent(EventType.CHANGE_EQUIP, role, null));
        SpringUtils.getBroadcastService().sendUpdateAppear(role);
        int type = FlyTypeEnums.getType(fromEquip.getName());
        if(type>0){
            int oldtime = attrService.getValue(fromEquip.getFields().get((short) 1).getField().get((short) 887).getValue()) ;
            if( oldtime == 0){
                fromEquip.getFields().get((short) 1).getField().get((short) 887).setValue((int)(System.currentTimeMillis()/1000) + 86400*30);
                fromEquip.getFields().get((short) 1).getField().get((short) 270).setValue(2);
                fromEquip.getFields().get((short) 1).getField().get((short) 284).setValue(0);
            }

            Team team = SpringUtils.getTeamService().getTeam(role.getRoleId());
            if (team != null && SpringUtils.getTeamService().isTeamLeader(role)) {
                for( Member member : team.getList()){
                    if (member == null) {
                        continue;
                    }
                    /**暂离的不用判断*/
                    if (member.isInTeam() == false) {
                        continue;
                    }

                    Role memberRole = SpringUtils.getRoleService().getOnlinePlayer(member.getRoleId());
                    if (memberRole == null) {
                        continue;
                    }

                    SpringUtils.getBroadcastService().sendUpdateAppear(memberRole);

                }
            }
        }

        role.save();
    }
}
